package com.sto.stoapp.file;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.util.Helper;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

/**
 * 实名制文件
 * @author Administrator
 *
 */
public class SmzFile {
	private static final int ACTION_DIS_CANCEL_FINISH = 0X5A; // 都屏蔽
	private Context context;
	private File file = null;
	public SmzFile(Context context) {
		this.context = context;
	}

    private Handler handler  = new Handler(Looper.getMainLooper());

	public boolean findIsZJSiteCode(String siteCode){
		boolean ret = false;
		File file = null;
		if(siteCode == null || "".equals(siteCode)){
			
			return false;
		}
		try{
			file = new File(
				Environment.getExternalStorageDirectory(),
				"site_zj.txt");
		}catch(Exception ex){
			return false;
		}
		if(file.exists()){
			try{
				FileReader fr = new FileReader(file);
				String s = null;
				while( (s = readLine(fr)) !=null ){
					if(s.equals(siteCode)){
						ret = true;
						break;
					}
				}
				fr.close();
				
			}catch(Exception ex){
				
			}
			
			
		}
		
		return ret;
	}
	
	
	private String readLine(Reader fr){
		int num =0;
		StringBuffer sb=new StringBuffer();
		try{
			while((num=fr.read())!=-1){
				if(num=='\r')
					continue;
				else if( num=='\n'){
					return sb.toString();//返回读取的一行字符串
					}else{
						sb.append((char)num);
					}
				}
			}catch (IOException e){
				e.printStackTrace();
				return null;
			}
		//防止文本末尾没加回车换行符，以丢失文本内容
		if( sb.length()>0){
			return sb.toString();
			}
		return null;
	}
	
	/**
	 * 设置超时时间和创建httpClient
	 * 
	 * @return
	 */
	private HttpClient setTimeOutClient() {
		HttpParams params = new BasicHttpParams(); // 实例化Post参数对象
		HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);// 设置请求超时
		HttpConnectionParams.setSoTimeout(params, 120 * 1000); // 设置响应超时
		HttpClient client = new DefaultHttpClient(params); // 实例化一个连接对象
		return client;
	}

	/**
	 * 下载浙江网点资料
	 */
	public void downSmzZjSiteCodeFile(final boolean isNotice){
		try{
			file = new File(
					Environment.getExternalStorageDirectory(),
					"site_zj.txt");
		}catch(Exception ex){
			return;
		}
		// 每次登陆都更新下载
//		if(file.exists()){
//            file.delete();
//			return;
//		}
		new Thread(){
			public void run() {
                downfile("site_zj.txt", "http://pda.sto.cn:9543/downloadfile/site_zj.txt");
                if (isNotice) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Helper.showToast(context, "实名制网点下载完成");
                        }
                    });
                }
            };
		}.start();
	}
	
	/**
	 * 下载实名制插件并安装
	 */
	public boolean downSmzZjFile(){
		try{
			file = new File(
					Environment.getExternalStorageDirectory(),
					"site_zj.apk");
		}catch(Exception ex){
			return false;
		}
		if(downfile("site_zj.apk", "http://pda.sto.cn:9543/downloadfile/OCR_ZJ.apk")){
			openFile(file);
			return true;
		}
		return true;
	}
	
	private void openFile(File file) {
		StoApplication.getStoJni().StoJNI_InstallApkWithSilence(file.getPath(), false);
		/*KaicomJNI.getInstance(context).CfgInstallManager(
				ACTION_DIS_CANCEL_FINISH);

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		context.startActivity(intent);*/
	}
	
	public boolean downfile(String fileName, String uri) {
		boolean ret = false;
		
		HttpClient client = setTimeOutClient();
		HttpGet get = null;
		try {
			// 取得HTTP response
			get = new HttpGet(uri);
			HttpResponse httpResponse = client.execute(get);
			int status = httpResponse.getStatusLine().getStatusCode();
			// 若状态码为200 ok
			if (status == 200) {
				try {
					HttpEntity entity = httpResponse.getEntity();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
						}
						fileOutputStream.flush();
						if (fileOutputStream != null) {
							fileOutputStream.close();
						}
						ret = true;
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();

				} catch (IOException e) {

					e.printStackTrace();
				}
			}
		} catch (Exception e) {

		}
		
		return ret;
	}
}
